<?php
/**********************************************************************************
WIKINDX: Bibliographic Management system.
Copyright (C)

This program is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program;
if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

The WIKINDX Team 2006
sirfragalot@users.sourceforge.net
**********************************************************************************/
/*****
*	RESOURCEWRITE class
*
*	Write new or edited resources
*
*	$Header: /cvsroot/wikindx/wikindx3/core/resource/RESOURCEWRITE.php,v 1.46 2007/10/09 09:55:36 sirfragalot Exp $
*****/
class RESOURCEWRITE
{
// Constructor
	function RESOURCEWRITE($db, $vars)
	{
		$this->db = $db;
		$this->vars = $vars;
		include_once("core/session/SESSION.php");
		$this->session = new SESSION();
		include_once("core/template/TEMPLATE.php");
		$this->template = new TEMPLATE('content');
		include_once("core/messages/ERRORS.php");
		$this->errors = new ERRORS();
		include_once("core/messages/MESSAGES.php");
		$this->messages = new MESSAGES();
// At this stage, if sessionVar['title'] is missing, the user has hit the back button following a 
// successful write/edit -- we need to block a further write.
		if(!$this->session->getVar('resource_title'))
		{
			include_once("core/html/CLOSE.php");
			$this->template->setVar('heading', $this->messages->text("heading", "resources"));
			$this->template->setVar('body', $this->errors->text("done", "resource"));
			new CLOSE($this->db, $this->template->process());
		}
		include_once("core/messages/SUCCESS.php");
		$this->success = new SUCCESS();
		include_once("core/html/HTML.php");
		$this->html = new HTML();
		include_once("core/html/MISC.php");
		include_once("core/publisher/PUBLISHER.php");
		$this->publisher = new PUBLISHER($this->db);
		include_once("core/collection/COLLECTION.php");
		$this->collection = new COLLECTION($this->db);
		include_once("core/creator/CREATOR.php");
		$this->creator = new creator($this->db);
// by default, we INSERT a new resource.  If this is FALSE, we are editing and therefore need to UPDATE
		if($this->resourceId = $this->session->getVar('resource_resourceId'))
		{
// we're editing
			$this->insert = FALSE;
			$this->resourceAutoId = $this->resourceId;
		}
		else
// we're inserting a new resource
		{
			$this->insert = TRUE;
			$this->resourceId = 0;
			$this->resourceAutoId = FALSE;
		}
		$this->publisherAutoId = FALSE;
		$this->confPublisherAutoId = FALSE;
		$this->collectionAutoId = FALSE;
	}
	function writeResource()
	{
		include_once("core/resource/VALIDATEINPUT.php");
		$validate = new VALIDATEINPUT($this->db, $this->vars, $this);
		if($this->insert)
			$this->template->setVar('heading', $this->messages->text("heading", "newResource"));
		else
			$this->template->setVar('heading', $this->messages->text("heading", "editResource"));
		$sessionVars = $validate->stage3();
//print "HERE: "; print_r($sessionVars); die;
		unset($validate);
		$this->startWrite($sessionVars);
		unset($sessionVars);
		include_once("core/notify/NOTIFY.php");
		$notify = new NOTIFY($this->db);
		$resourceId = $this->resourceId ? $this->resourceId : $this->resourceAutoId;
		$notify->email($resourceId, $this->insert);
		if($this->session->getVar("resource_typeConvert"))
			$success = $this->success->text("convertType");
		else
			$success = $this->success->text("resource", " " . $this->messages->text("misc", "edited") . " ");
// finally, clear session
// clear the session but keep resource_type
		$this->session->delVar("resourceEditRow");
		$type = $this->session->getVar('resource_type');
		$this->session->clearArray("resource");
		if($type)
			$this->session->setVar('resource_type', $type);
		if($this->insert)
		{
			include_once("core/resource/RESOURCE.php");
			$resource = new RESOURCE($this->db, $this->vars);
			return $resource->gateKeep('newResource', $this->success->text("resource", 
			" " . $this->messages->text("misc", "added") . " "));
		}
		else
		{
			if($this->session->getVar('sql_lastView') == 'solo')
			{
// send back to view this resource with success message
				include_once("core/resource/RESOURCEVIEW.php");
				$resource = new RESOURCEVIEW($this->db, $this->vars);
				new CLOSE($this->db, $resource->view($success, 'lastSolo'));
			}
// send back to resource list with success message
			else if($this->session->getVar('sql_lastView') == 'multi')
			{
				include_once("core/user/MYWIKINDX.php");
				$mywikindx = new MYWIKINDX($this->db, $this->vars);
// send back to view this resource with success message
				return $mywikindx->chooseDisplay($success);
			}
// Just in case - send back to blank page with success message
			else
				$this->template->setVar('body', $success);
		}
		return $this->template->process();
	}
// write resource table by table.
// Ensure that all input (except textarea (i.e. notes)) is parsed by html->nlReduce().
	function startWrite($sessionVars)
	{
//print_r($sessionVars); die;
		$this->userId = $this->session->getVar('setup_userId');
		$typeConvert = $this->session->getVar("resource_typeConvert");
		$this->loadMap($sessionVars);
		$this->writeResourceTable($sessionVars);
//		if(!$typeConvert)
//		{
			$creatorIds = $this->creator->writeCreatorTable($sessionVars);
			$this->writeResourceCreatorTable($creatorIds);
//		}
		$this->creator->removeHanging();
		unset($this->creator);
		$this->publisherAutoId = $this->publisher->writePublisherTable($sessionVars);
		$this->transPublisherAutoId = $this->publisher->writeTransPublisherTable($sessionVars);
// proceedings_article and proceedings can also have publisher details in addition to organiser details
		if(($sessionVars['type'] == 'proceedings_article') || ($sessionVars['type'] == 'proceedings'))
			$this->confPublisherAutoId = $this->publisher->writePublisherTable($sessionVars, FALSE, TRUE);
		$collectionVars = $sessionVars;
		if($creatorIds)
		{
			foreach($creatorIds as $type => $array)
			{
				if($type == 'creator1')
					continue;
				$collectionVars[$type] = join(',', $array);
			}
		}
		if(!$this->collectionAutoId = $this->session->getVar('resource_collectionId'))
			$this->collectionAutoId = $this->collection->writeCollectionTable($collectionVars, 
			$this->publisherAutoId, $this->confPublisherAutoId, $this->transPublisherAutoId);
		unset($collectionVars);
		$this->writePageTable($sessionVars);
		$this->writeYearTable($sessionVars);
		$this->writeMiscTable($sessionVars);
		$this->writeUserBib($sessionVars);
		$this->writeCategoryTable($sessionVars);
		include_once("core/keyword/KEYWORD.php");
		$this->keyword = new KEYWORD($this->db);
		$keywordIds = $this->keyword->writeKeywordTable($sessionVars);
		$this->writeKeywordTable($keywordIds);
		unset($this->keyword);
		$this->writeNoteTable($sessionVars);
		$this->writeAbstractTable($sessionVars);
		$this->writeCustomTable($sessionVars);
		$this->addToCollection();
		if($this->insert)
			$this->writeSummaryTable();
		else
		{
// If we're editing and this resource had a publisher but that has been removed here, need to check that that 
// publisher is still used in other resources else we remove it entirely.
// ditto for collection (must be done first as 'collectionString' is searched for publishers
			$this->collection->removeHanging();
			$this->publisher->removeHanging();
			unset($this->publisher, $this->collection);
		}
		$this->writeTimestampTable();
		$this->writeBibtexKey();
// Lock re-inserting
//		$this->session->setVar('resourceLock', TRUE);
	}
// Adding a new or converted resource to an existing collection
	function addToCollection()
	{
		if($collectionId = $this->session->getVar('resource_collectionId'))
		{
			$recordset = $this->db->select(array('WKX_collection'), 
				array('collectionType', 'collectionString'), 
				' WHERE ' . $this->db->formatField('id') . '=' . $this->db->tidyInput($collectionId) . 
				' AND ' . $this->db->formatField('collectionString') . ' IS NOT NULL');
			if($this->db->numRows($recordset))
			{
				$row = $this->db->fetchRow($recordset);
				$type = $row['collectionType'];
				$stringArray = unserialize(base64_decode($row['collectionString']));
				$updateResource = $updateMisc = $updateCreator = $updateYear = array();
				include_once("core/collection/COLLECTIONMAP.php");
				$collectionMap = new COLLECTIONMAP();
				foreach($stringArray as $key => $value)
				{
					if(array_key_exists($key, $collectionMap->{$type}['resource']))
						$updateResource[$key] = $value;
					else if(array_key_exists($key, $collectionMap->{$type}['resource_misc']))
						$updateMisc[$key] = $value;
					else if(array_key_exists($key, $collectionMap->{$type}['resource_year']))
						$updateYear[$key] = $value;
					else if(array_key_exists($key, $collectionMap->{$type}['resource_creator']))
						$updateCreator[$key] = $value;
				}
				if(!empty($updateResource))
					$this->db->update('WKX_resource', $updateResource, 
						' WHERE ' . $this->db->formatField('id') . '=' . 
						$this->db->tidyInput($this->resourceAutoId));
				if(!empty($updateMisc))
					$this->db->update('WKX_resource_misc', $updateMisc, 
						' WHERE ' . $this->db->formatField('id') . '=' . 
						$this->db->tidyInput($this->resourceAutoId));
// resource_year and resource_creator may not yet have a row for this resource
				if(!empty($updateYear))
				{
					$recordset = $this->db->select(array('WKX_resource_year'), 'id', 
						' WHERE ' . $this->db->formatField('id') . '=' . 
						$this->db->tidyInput($this->resourceAutoId));
					if($this->db->numRows($recordset))
						$this->db->update('WKX_resource_year', $updateYear, 
							' WHERE ' . $this->db->formatField('id') . '=' . 
							$this->db->tidyInput($this->resourceAutoId));
					else // insert
					{
						$fields = $values = array();
						$fields[] = 'id';
						$values[] = $this->resourceAutoId;
						foreach($updateYear as $key => $value)
						{
							$fields[] = $key;
							$values[] = $value;
						}
						$this->db->insert('WKX_resource_year', $fields, $values);
					}
				}
				if(!empty($updateCreator))
				{
					$recordset = $this->db->select(array('WKX_resource_creator'), 'id', 
						' WHERE ' . $this->db->formatField('id') . '=' . 
						$this->db->tidyInput($this->resourceAutoId));
					if($this->db->numRows($recordset))
						$this->db->update('WKX_resource_creator', $updateCreator, 
							' WHERE ' . $this->db->formatField('id') . '=' . 
							$this->db->tidyInput($this->resourceAutoId));
					else // insert
					{
						$fields = $values = array();
						$fields[] = 'id';
						$values[] = $this->resourceAutoId;
						foreach($updateCreator as $key => $value)
						{
							$fields[] = $key;
							$values[] = $value;
						}
						$this->db->insert('WKX_resource_creator', $fields, $values);
					}
				}
			}
		}
	}
// Load mappings between resource types and database tables where there is no specifically named field.
// Additionally, if converting a resource type, remove extra creators from sessionVars
	function loadMap(&$sessionVars)
	{
		include_once("core/resource/RESOURCEMAP.php");
		$map = new RESOURCEMAP();
		$type = $sessionVars['type'];
		$this->map = $map->$type;
		$triage = $unset = array();
		if($oldType = $this->session->getVar("resource_oldType"))
		{
			foreach($map->{$oldType}['resource_creator'] as $key => $value)
			{
				if(!array_key_exists($key, $this->map['resource_creator']))
					$triage[] = $key;
			}
			foreach($triage as $creatorDelete)
			{
				foreach($sessionVars as $key => $value)
				{
					if(preg_match("/^$creatorDelete/", $key))
						$unset[] = $key;
				}
				foreach($unset as $key)
					unset($sessionVars[$key]);
			}
		}
	}
// write WKX_resource and grab lastautoID
	function writeResourceTable($sessionVars)
	{
//print_r($sessionVars); print "<P>";
		include_once("core/messages/LANGUAGE.php");
		$noSortArray = LANGUAGE::noSort();
		$foundNoSort = $foundTransNoSort = FALSE;
		$fields[] = "type";
		$values[] = $sessionVars['type'];
		$fields[] = "title";
		$values[] = trim($this->html->removeNl($sessionVars['title']));
		if(array_key_exists('noSort', $sessionVars))
		{
			$fields[] = "noSort";
			$values[] = trim($this->html->removeNl($sessionVars['noSort']));
		}
		else
			$nulls[] = "noSort";
// subtitle
		if(array_key_exists('subtitle', $sessionVars))
		{
			$fields[] = "subtitle";
			$values[] = trim($this->html->removeNl($sessionVars['subtitle']));
		}
		else
			$nulls[] = "subtitle";
// short title
		if(array_key_exists('shortTitle', $sessionVars))
		{
			$fields[] = "shortTitle";
			$values[] = trim($this->html->removeNl($sessionVars['shortTitle']));
		}
		else
			$nulls[] = "shortTitle";
// for books and book_articles, titles of original work from which translation has been made.
		if(array_key_exists('transTitle', $sessionVars))
		{
			$fields[] = "transTitle";
			$values[] = trim($this->html->removeNl($sessionVars['transTitle']));
		}
		else
			$nulls[] = "transTitle";
		if(array_key_exists('transSubtitle', $sessionVars))
		{
			$fields[] = "transSubtitle";
			$values[] = trim($this->html->removeNl($sessionVars['transSubtitle']));
		}
		else
			$nulls[] = "transSubtitle";
		if(array_key_exists('transNoSort', $sessionVars))
		{
			$fields[] = "transNoSort";
			$values[] = trim($this->html->removeNl($sessionVars['transNoSort']));
		}
		else
			$nulls[] = "transNoSort";
// URL
		if(array_key_exists('url', $sessionVars) && trim($sessionVars['url']))
		{
			$fields[] = "url";
			$values[] = trim($this->html->removeNl($sessionVars['url']));
		}
		else
			$nulls[] = "url";
// DOI
		if(array_key_exists('doi', $sessionVars) && trim($sessionVars['doi']))
		{
			$fields[] = "doi";
			$doi = trim($this->html->removeNl($sessionVars['doi']));
			$values[] = preg_replace("/http:\/\/dx.doi.org\/|dx.doi.org\//i", '', $doi);
		}
		else
			$nulls[] = "doi";
// ISBN
		if(array_key_exists('isbn', $sessionVars) && trim($sessionVars['isbn']))
		{
			$fields[] = "isbn";
			$values[] = trim($this->html->removeNl($sessionVars['isbn']));
		}
		else
			$nulls[] = "isbn";

// fields 'field1' .. 'field9'
//		$fieldList = array_keys($this->map['resource']);
		$fieldList = array('field1', 'field2', 'field3', 'field4', 'field5', 
			'field6', 'field7', 'field8', 'field9');
		foreach($fieldList as $field)
		{
			if(array_key_exists($field, $sessionVars) && 
				$fieldValue = trim($this->html->removeNl($sessionVars[$field])))
			{
				$fields[] = $field;
				$values[] = $fieldValue;
			}
// else, updating to be set to NULL
			else
				$nulls[] = $field;
		}
		if($this->insert)
			$this->db->insert('WKX_resource', $fields, $values);
		else
		{
			foreach($fields as $field)
				$updateArray[$field] = array_shift($values);
			$this->db->update('WKX_resource', $updateArray, 
				" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
		}
		if($this->insert)
			$this->resourceAutoId = $this->db->lastAutoId('WKX_resource');
		if(isset($nulls) && !empty($nulls))
			$this->db->updateNull('WKX_resource', $nulls, 
				" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
	}
// Write the bibtexKey field for new or edited resources
	function writeBibtexKey()
	{
		include_once("core/file/BIBTEXCONFIG.php");
		$config = new BIBTEXCONFIG();
		$config->bibtex();
		$recordset = $this->db->select(array('WKX_resource'), 'bibtexKey');
		while($row = $this->db->loopRecordSet($recordset))
			$bibtexKeys[] = $row['bibtexKey'];
		$letters = range('a', 'z');
		$sizeof = sizeof($letters);
		$recordset = $this->db->select(array('WKX_resource_misc'), 
			array(array('WKX_resource_misc.id' => 'resourceId'), 'creator1', 'creator2', 'year1'), 
			" LEFT JOIN " . $this->db->formatTable('WKX_resource_creator') . ' ON ' . 
			$this->db->formatField('WKX_resource_misc.id') . '=' . 
			$this->db->formatField('WKX_resource_creator.id') . 
			" LEFT JOIN " . $this->db->formatTable('WKX_resource_year') . ' ON ' . 
			$this->db->formatField('WKX_resource_misc.id') . '=' . 
			$this->db->formatField('WKX_resource_year.id') . 
			' WHERE ' . $this->db->formatField('WKX_resource_misc.id') . "=" . $this->resourceAutoId);
		$row = $this->db->fetchRow($recordset);
		$year = $row['year1'];
		if(!$row['creator1'] && $row['creator2']) // use editor
			$creatorId = array_shift(split(',', $row['creator2']));
		else
			$creatorId = array_shift(split(',', $row['creator1']));
		$recordset2 = $this->db->select(array('WKX_creator'), array('prefix', 'surname'), 
			' WHERE ' . $this->db->formatField('WKX_creator.id') . '=' . 
			$this->db->tidyInput($creatorId));
		$keyMade = FALSE;
		if(!$this->db->numRows($recordset2)) // anonymous
			$base = 'anon' . $year;
		else
		{
			$creator = $this->db->fetchRow($recordset2);
			$prefix = '';
			if($creator['prefix'])
			{
				$prefix = utf8_decode($creator['prefix']);
				foreach($config->bibtexSpChPlain as $key => $value)
				{
					$char = chr($key);
					$prefix = preg_replace("/$char/", "$value", $prefix);
				}
				$prefix = preg_replace("/\W/", '', $prefix);
			}
			$surname = utf8_decode($creator['surname']);
			foreach($config->bibtexSpChPlain as $key => $value)
			{
				$char = chr($key);
				$surname = preg_replace("/$char/", "$value", $surname);
			}
			$surname = preg_replace("/\W/", '', $surname);
			$base = $prefix . $surname . $year;
		}
		$bibtexKey = $base;
		for($i = 0; $i < $sizeof; $i++)
		{
			if(array_search($bibtexKey, $bibtexKeys) === FALSE)
			{
				$keyMade = TRUE;
				break;
			}
			$bibtexKey = $base . $letters[$i];
		}
		if(!$keyMade)
			$bibtexKey = $base . '.' . $this->resourceAutoId; // last resort
		$this->db->updateSingle('WKX_resource', 
			$this->db->formatField('bibtexKey') .  "=" . $this->db->tidyInput($bibtexKey),
			" WHERE " . $this->db->formatField('id') . "=" . $this->resourceAutoId);
	}
// write WKX_resource_misc
	function writeMiscTable($sessionVars)
	{
		$fieldList = array('miscField1', 'miscField2', 'miscField3', 'miscField4', 
			'miscField5', 'miscField6');
		$nulls = array();
		if(!$this->insert)
			$editRow = unserialize($this->session->getVar("resourceEditRow"));
		foreach($fieldList as $field)
		{
			if(array_key_exists($field, $sessionVars) && trim($sessionVars[$field]) && ($field != 'miscField1'))
			{
				$fields[] = $field;
				$values[] = trim($this->html->removeNl($sessionVars[$field]));
			}
// else, updating to be set to NULL
			else
				$nulls[] = $field;
		}
// if in multi user mode, add this user's id
		if($this->insert && $this->userId)
		{
			$fields[] = "addUserIdResource";
			$values[] = $this->userId;
		}
		else if($this->userId)
		{
			$fields[] = "editUserIdResource";
			$values[] = $this->userId;
		}
		if($this->publisherAutoId)
		{
			$fields[] = "publisher";
			$values[] = $this->publisherAutoId;
		}
		else
			$nulls[] = 'publisher';
		if($this->collectionAutoId)
		{
// If converting a resource belonging to a collection to a resource type that may have no collections, be sure to set 'collection' field to NULL
			include_once("core/collection/COLLECTIONMAP.php");
			$collectionMap = new COLLECTIONMAP();
			$type = $sessionVars['type'];
			if(array_key_exists($type, $collectionMap->collectionTypes))
			{
				$fields[] = "collection";
				$values[] = $this->collectionAutoId;
			}
			else
				$nulls[] = 'collection';
		}
		else
			$nulls[] = 'collection';
		if($this->transPublisherAutoId)
		{
			$fields[] = "miscField1";
			$values[] = $this->transPublisherAutoId;
		}
		else if(array_search('miscField1', $nulls) === FALSE)
			$nulls[] = 'publisher';
		if($this->confPublisherAutoId)
		{
			$fields[] = "miscField1";
			$values[] = $this->confPublisherAutoId;
			if(array_search('miscField1', $fieldList) === FALSE)
				array_push($fieldList, "miscField1");
		}
		else if(array_search('miscField1', $nulls) === FALSE)
			$nulls[] = 'miscField1';
		if($this->confPublisherAutoId)
			unset($nulls[array_search('miscField1', $nulls)]);
		$fields[] = "peerReviewed";
		if(array_key_exists('peerReviewed', $sessionVars))
			$values[] = 'Y';
		else
			$values[] = 'N';
//print "HERE: " . $sessionVars['peerReviewed'] . "<P>";
		if(isset($fields))
		{
			$recordset = $this->db->select(array('WKX_resource_misc'), array('id'), 
				" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
			if($this->db->numRows($recordset)) // update/edit
			{
				foreach($fields as $field)
					$updateArray[$field] = array_shift($values);
				$this->db->update('WKX_resource_misc', $updateArray, 
					" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
			}
			else // newinsert
			{
				$fields[] = "id";
				$values[] = $this->resourceAutoId;
				$this->db->insert('WKX_resource_misc', $fields, $values);
			}
		}
		else
		{
			$recordset = $this->db->select(array('WKX_resource_misc'), array('publisher', 'collection'), 
				" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
			$row = $this->db->fetchRow($recordset);
			$this->db->delete('WKX_resource_misc', 
				" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
			$this->db->optimize('WKX_resource_misc');
			return;
		}
		if(!$this->insert && isset($nulls) && !empty($nulls))
		{
			$this->db->updateNull('WKX_resource_misc', $nulls, 
				" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
		}
	}
// write WKX_resource_page
	function writePageTable($sessionVars)
	{
		$fieldList = array("pageStart", "pageEnd");
		foreach($fieldList as $field)
		{
			if(array_key_exists($field, $sessionVars))
			{
				$fields[] = $field;
				$values[] = trim($this->html->removeNl($sessionVars[$field]));
			}
// else, updating to be set to NULL
			else
				$nulls[] = $field;
		}
		if(isset($fields))
		{
			$recordset = $this->db->select(array('WKX_resource_page'), array('id'), 
				" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
			if($this->db->numRows($recordset))
			{
				foreach($fields as $field)
					$updateArray[$field] = array_shift($values);
				$this->db->update('WKX_resource_page', $updateArray, 
					" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
			}
			else
			{
				$fields[] = "id";
				$values[] = $this->resourceAutoId;
				$this->db->insert('WKX_resource_page', $fields, $values);
			}
		}
		else
		{
			$this->db->delete('WKX_resource_page', 
				" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
			$this->db->optimize('WKX_resource_page');
			return;
		}
		if(isset($nulls) && !empty($nulls))
			$this->db->updateNull('WKX_resource_page', $nulls, 
				" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
	}
// write to WKX_resource_creator
	function writeResourceCreatorTable($creatorIds)
	{
		if(!$creatorIds)
		{
			$this->db->delete('WKX_resource_creator', 
				" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
			$this->db->optimize('WKX_resource_creator');
			return;
		}
		foreach($creatorIds as $type => $idArray)
		{
			$fields[] = $type;
			$values[] = implode(',', $idArray);
		}
		$types = array("creator1", "creator2", "creator3", "creator4", "creator5",);
		if(isset($fields))
		{
			$nulls = array_diff($types, $fields);
			$recordset = $this->db->select(array('WKX_resource_creator'), array('id'), 
				" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
			if($this->resourceId && $this->db->numRows($recordset))
			{
				foreach($fields as $field)
					$updateArray[$field] = array_shift($values);
				$this->db->update('WKX_resource_creator', $updateArray, 
					" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
			}
			else
			{
				$fields[] = "id";
				$values[] = $this->resourceAutoId;
				$this->db->insert('WKX_resource_creator', $fields, $values);
			}
		}
		if(isset($nulls) && !empty($nulls))
			$this->db->updateNull('WKX_resource_creator', $nulls, 
				" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
	}
// write to WKX_resource_abstract
	function writeAbstractTable($sessionVars)
	{
		if(!array_key_exists('abstract', $sessionVars))
		{
			if(!$this->insert)
			{
				$this->db->delete('WKX_resource_abstract', 
					" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
				$this->db->optimize('WKX_resource_abstract');
			}
			return;
		}
		$fields[] = "abstract";
		$values[] = trim($sessionVars['abstract']);
		$recordset = $this->db->select(array('WKX_resource_abstract'), array('id'), 
			" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
		if($this->db->numRows($recordset))
		{
			foreach($fields as $field)
				$updateArray[$field] = array_shift($values);
// if in multi user mode, add this user's id
			if($this->userId)
				$updateArray["editUserIdAbstract"] = $this->userId;
			$this->db->update('WKX_resource_abstract', $updateArray, 
				" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
		}
		else
		{
			$fields[] = "id";
			$values[] = $this->resourceAutoId;
// if in multi user mode, add this user's id
			if($this->userId)
			{
				$fields[] = "addUserIdAbstract";
				$values[] = $this->userId;
			}
			$this->db->insert('WKX_resource_abstract', $fields, $values);
		}
	}
// write to WKX_resource_note
	function writeNoteTable($sessionVars)
	{
		if(!array_key_exists('note', $sessionVars))
		{
			if(!$this->insert)
			{
				$this->db->delete('WKX_resource_note', 
					" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
				$this->db->optimize('WKX_resource_note');
			}
			return;
		}
		$fields[] = "text";
		$values[] = trim($sessionVars['note']);
		$recordset = $this->db->select(array('WKX_resource_note'), array('id'), 
			" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
		if($this->db->numRows($recordset))
		{
			foreach($fields as $field)
			$updateArray[$field] = array_shift($values);
// if in multi user mode, add this user's id
			if($this->userId)
				$updateArray["editUserIdNote"] = $this->userId;
			$this->db->update('WKX_resource_note', $updateArray, 
				" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
		}
		else
		{
			$fields[] = "id";
			$values[] = $this->resourceAutoId;
// if in multi user mode, add this user's id
			if($this->userId)
			{
				$fields[] = "addUserIdNote";
				$values[] = $this->userId;
			}
			$this->db->insert('WKX_resource_note', $fields, $values);
		}
	}
// write to WKX_resource_category
	function writeCategoryTable($sessionVars)
	{
		$fields[] = "categories";
// force to 'General' group if no group selected.
		if(!array_key_exists('group_ids', $sessionVars))
			$values[] = 1;
		else
			$values[] = trim($sessionVars['group_ids']);
		$recordset = $this->db->select(array('WKX_resource_category'), array('id'), 
			" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
		if($this->db->numRows($recordset))
		{
			foreach($fields as $field)
				$updateArray[$field] = array_shift($values);
			$this->db->update('WKX_resource_category', $updateArray, 
				" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
		}
		else
		{
			$fields[] = "id";
			$values[] = $this->resourceAutoId;
			$this->db->insert('WKX_resource_category', $fields, $values);
		}
	}
// write to WKX_resource_keyword
	function writeKeywordTable($keywordIds)
	{
		$checkKeywords = FALSE;
// Current keywords for this resource
		$recordset = $this->db->select(array('WKX_resource_keyword'), array('keywords'), 
			" WHERE " . $this->db->formatfield('id') . "=" . 
			$this->db->tidyInput($this->resourceId));
		$oldRow = $this->db->fetchRow($recordset);
		if(!$keywordIds || empty($keywordIds))
		{
			$checkKeywords = $oldRow['keywords'];
			$this->db->delete('WKX_resource_keyword', 
				" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
			$this->db->optimize('WKX_resource_keyword');
			$this->keyword->removeHanging2($checkKeywords);
			return;
		}
		else if(!empty($oldRow))
			$checkKeywords = array_diff(explode(",", $oldRow['keywords']), $keywordIds);
		$fields[] = "keywords";
		$values[] = implode(',', $keywordIds);
		$recordset = $this->db->select(array('WKX_resource_keyword'), array('id'), 
			" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
		if($this->db->numRows($recordset))
		{
			$updateArray['keywords'] = array_shift($values);
			$this->db->update('WKX_resource_keyword', $updateArray, 
				" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
		}
		else
		{
			$fields[] = "id";
			$values[] = $this->resourceAutoId;
			$this->db->insert('WKX_resource_keyword', $fields, $values);
		}
// remove keyword(s) if they no longer have resource attached to them
		if($checkKeywords)
			$this->keyword->removeHanging2(join(",", $checkKeywords));
	}
// Write to WKX_resource_year
	function writeYearTable($sessionVars)
	{
		$fieldList = array('year1', 'year2', 'year3', 'year4');
		foreach($fieldList as $field)
		{
			if(array_key_exists($field, $sessionVars))
			{
				$fields[] = $field;
				$values[] = trim($this->html->removeNl($sessionVars[$field]));
			}
			else
				$nulls[] = $field;
		}
		if(isset($fields))
		{
			$recordset = $this->db->select(array('WKX_resource_year'), array('id'), 
				" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
			if($this->db->numRows($recordset))
			{
				foreach($fields as $field)
					$updateArray[$field] = array_shift($values);
				$this->db->update('WKX_resource_year', $updateArray, 
					" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
			}
			else
			{
				$fields[] = "id";
				$values[] = $this->resourceAutoId;
				$this->db->insert('WKX_resource_year', $fields, $values);
			}
		}
		else
		{
			$this->db->delete('WKX_resource_year', 
				" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
			$this->db->optimize('WKX_resource_year');
			return;
		}
		if(isset($nulls) && !empty($nulls))
			$this->db->updateNull('WKX_resource_year', $nulls, 
				" WHERE " . $this->db->formatField('id') . "=" . $this->resourceId);
	}
// write to WKX_resource_custom
	function writeCustomTable($sessionVars)
	{
		$custom = array();
		foreach($sessionVars as $key => $value)
		{
// expect 'custom_size_id' where size is 'S' or 'L' and 'id' is the id from `WKX_custom`
			$split = split("custom_", $key);
			if(sizeof($split) == 2)
			{
				$split2 = split("_", $split[1]);
				if(sizeof($split2) != 2)
					continue;
				if($split2[0] == 'S')
					$size[] = 'custom_short';
				else
					$size[] = 'custom_long';
				$custom[$split2[1]] = trim($value);
			}
		}
		if(empty($custom) && $this->insert)
			return;
		if(!$this->insert) // Editing
		{
			$writeKeys = array_keys($custom);
			$recordset = $this->db->select(array('WKX_resource_custom'), array('customId'), 
				" WHERE " . $this->db->formatField('resourceId') . "=" . 
				$this->db->tidyInput($this->resourceAutoId));
			while($row = $this->db->loopRecordSet($recordset))
				$storedKeys[] = $row['customId'];
			if(isset($storedKeys))
			{
				$removeKeys = array_diff($storedKeys, $writeKeys);
				foreach($removeKeys as $customId)
					$this->db->delete('WKX_resource_custom', 
						" WHERE " . $this->db->formatField('customId') . "=" . $this->db->tidyInput($customId) . 
						" AND " . $this->db->formatField('resourceId') . "=" . 
						$this->db->tidyInput($this->resourceAutoId));
			}
		}
		foreach($custom as $id => $text)
		{
			$recordset = $this->db->select(array('WKX_resource_custom'), array('id'), 
				" WHERE " . $this->db->formatField('customId') . "=" . $this->db->tidyInput($id) . 
				" AND " . $this->db->formatField('resourceId') . "=" . 
				$this->db->tidyInput($this->resourceAutoId));
			if($this->db->numRows($recordset) && !$this->insert)
			{
				$updateArray = array();
				if($this->userId)
					$updateArray["editUserIdCustom"] = $this->userId;
				$field = array_shift($size);
				$updateArray[$field] = $text;
				$this->db->update("WKX_resource_custom", $updateArray, 
					" WHERE " . $this->db->formatField('customId') . "=" . $this->db->tidyInput($id) . 
					" AND " . $this->db->formatField('resourceId') . "=" . 
					$this->db->tidyInput($this->resourceAutoId));
			}
			else // INSERT
			{
				$fields = $values = array();
// if in multi user mode, add this user's id
				if($this->userId)
				{
					$fields[] = "addUserIdCustom";
					$values[] = $this->userId;
				}
				$fields[] = "customId";
				$values[] = $id;
				$fields[] = "resourceId";
				$values[] = $this->resourceAutoId;
				$fields[] = array_shift($size);
				$values[] = $text;
				$this->db->insert('WKX_resource_custom', $fields, $values);
			}
		}
	}
// Add new resource to user bibliographies
	function writeUserBib($sessionVars)
	{
		if(!array_key_exists('bib_ids', $sessionVars))
			return; // do nothing
		$bibs = explode(',', $sessionVars['bib_ids']);
		if(empty($bibs) && !array_key_exists('removeFromBibliographies', $sessionVars)) // do nothing
			return;
		if(!$this->insert) // possibly udating user bibliographies
		{
			$recordSet = $this->db->select(array("WKX_user_bibliography"), 'id', 
				" WHERE " . $this->db->formatfield('userId') . "=" . $this->db->tidyInput($this->userId) . 
// NB MySQL bug: http://bugs.mysql.com/bug.php?id=2047 -- append comma temporarily
				" AND FIND_IN_SET(" . $this->db->tidyInput($this->resourceAutoId) . ", CONCAT(" . 
					$this->db->formatField('bibliography') . ", ','))");
			while($row = $this->db->loopRecordSet($recordSet))
				$existArray[] = $row['id'];
		}
		foreach($bibs as $bibId)
		{
			if(!$bibId)	// ID 0 == IGNORE
				continue;
			$bibIds[] = $bibId;
		}
		if(isset($bibIds) && isset($existArray) && !array_key_exists('removeFromBibliographies', $sessionVars))
		{
			$deleteMe = array_diff($existArray, $bibIds); // user bibliography IDs from which this resource is to be removed
			$bibIds = array_diff($bibIds, $existArray); // user bibliograhy IDs which remain to be updated with this resource
		}
		else if(array_key_exists('removeFromBibliographies', $sessionVars))
		{
			$deleteMe = $existArray;
			unset($bibIds);
		}
		if(isset($deleteMe))
		{
			foreach($deleteMe as $bibId)
			{
				$recordset = $this->db->select(array('WKX_user_bibliography'), array('bibliography'), 
					" WHERE " . $this->db->formatfield('id') . "=" . 
					$this->db->tidyInput($bibId));
// bibliography is a comma-separated list of unique resource ids.
				$dbBibs = $this->db->fetchOne($recordset);
				$dbBibs = explode(",", $dbBibs);
				unset($dbBibs[array_search($this->resourceAutoId, $dbBibs)]);
				if(empty($dbBibs))
					$this->db->updateNull('WKX_user_bibliography', array('bibliography'),
						" WHERE " . $this->db->formatfield('id') . "=" . 
						$this->db->tidyInput($bibId));
				else
				{
					$updateArray = array('bibliography' => implode(",", $dbBibs));
					$this->db->update('WKX_user_bibliography', $updateArray, 
						" WHERE " . $this->db->formatfield('id') . "=" . 
						$this->db->tidyInput($bibId));
				}
			}
		}
		if(!isset($bibIds))
			return;
// cleared to write to user bibliographies.
		foreach($bibIds as $bibId)
		{
			$recordset = $this->db->select(array('WKX_user_bibliography'), array('bibliography'), 
				" WHERE " . $this->db->formatfield('id') . "=" . $this->db->tidyInput($bibId));
// bibliography is a comma-separated list of unique resource ids.
			$dbBibsRow = $this->db->fetchOne($recordset);
			if(!$dbBibsRow)
				$updateArray = array('bibliography' => $this->resourceAutoId);
			else
			{
				$dbBibs = explode(",", $dbBibsRow);
				$dbBibs[] = $this->resourceAutoId;
				$updateArray = array('bibliography' => implode(",", $dbBibs));
			}
			$this->db->update('WKX_user_bibliography', $updateArray, 
				" WHERE " . $this->db->formatfield('id') . "=" . $this->db->tidyInput($bibId));
		}
// Update session
		include_once("core/user/USER.php");
		$user = new USER($this->db);
		$user->grabBibliographies();
	}
// Increment WKX_database_summary.totalResources
	function writeSummaryTable()
	{
		$this->db->updateSingle('WKX_database_summary', 
			$this->db->formatField('totalResources') .  "=" . 
			$this->db->formatField('totalResources') . "+" . $this->db->tidyInput(1));
	}
// Write timestamp
	function writeTimestampTable()
	{
		if($this->insert)
		{
			$fields[] = "id";
			$values[] = $this->resourceAutoId;
			$fields[] = 'timestamp';
			$values[] = $this->db->formatTimestamp();
			$fields[] = 'timestampAdd';
			$values[] = $this->db->formatTimestamp();
			$this->db->insert('WKX_resource_timestamp', $fields, $values);
		}
// updating
		else
// update resource timestamp
		$this->db->update('WKX_resource_timestamp', array('timestamp' => $this->db->formatTimestamp()), 
			" WHERE " . $this->db->formatField('id') . "=" . $this->db->tidyInput($this->resourceId));
	}
// Error handling.
	function failure($error)
	{
		include_once("core/html/CLOSE.php");
		new CLOSE($this->db, $error);
	}
}
?>
